/**
 * 
 */
package com.srini.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.srini.util.ConnectionUtil;
import com.srini.util.Constants;

/**
 * @author Sriniz
 * 
 */
public class DBMgmtServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String action = req.getParameter("action");
		resp.setContentType("application/json");
		PrintWriter out = resp.getWriter();
		req.getSession().getAttribute(Constants.LOGGEDIN_USER);
		JSONArray array = new JSONArray();
		JSONObject obj = new JSONObject();
		JSONObject mainObj = new JSONObject();
		System.out.println("........" + action);
		try {

			action = action == null ? "" : action;
			if (action.equalsIgnoreCase("loadTables")) {
				Connection con = new ConnectionUtil().getConnection();
				ResultSet rs = con.getMetaData().getTables(null, null, null,
						new String[] { "TABLE" });
				String key = null;
				while (rs.next()) {
					obj = new JSONObject();
					key = rs.getString("TABLE_NAME");
					obj.put("key", key);
					obj.put("value", key);
					array.put(obj);
				}
				mainObj.put("tables", array);
				array = new JSONArray();
				rs = con.createStatement().executeQuery(
						"select id, username from usertable");
				while (rs.next()) {
					obj = new JSONObject();
					obj.put("key", rs.getString(1));
					obj.put("value", rs.getString(2));
					array.put(obj);
				}
				mainObj.put("users", array);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.print(mainObj);
	}
}
